package com.zang.netty.biopool;

import com.zang.netty.bio.TimeServerHandler;
import com.zang.netty.model.enums.SocketEnum;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ·通过线程池创建
 * ·伪异步
 * @author Zhang Qiang
 * @Date 2019/7/18 17:47
 */
public class TimeServerByPool {

    public static void main(String[] args) throws IOException {

        int port = SocketEnum.PORT.getNum();

        if (args != null && args.length > 0){
            try {
                port = Integer.valueOf(args[0]);
            }catch (NumberFormatException e){
                //使用默认值
            }
        }
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("The time server is start in port :" + port);
            System.out.println("wait connection ..");
            Socket socket = null;
            // 创建I/O任务线程池
            TimeServerHandlerExecutePool singleExecutor  = new TimeServerHandlerExecutePool(50, 10000);
            //创建线程池之后由于线程池(maxPoolSize)和消息队列(queueSize)都是有界的，所以无论客户端并发连接数多大都不会导致线程数过多或者内存溢出
            for(;;){
                socket = serverSocket.accept();
                // 添加线程
                singleExecutor.execute(new TimeServerHandler(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null){
                System.out.println(" the time server close ");
                serverSocket.close();
                // 置空是为了让gc直接回收，但是需要其它地方也未定义其引用。
                serverSocket = null;
            }
        }
    }


}
